package com.guo.hui.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.guo.hui.model.shiro.TpUser;
import com.guo.hui.shiro.ShiroToken;

@Controller
@RequestMapping("/shang")
public class ServerController {

	@RequestMapping("/login")
	public String login() {
		return "common/login";
	}

	@ResponseBody
	@RequestMapping("/logindata")
	public String logindata(HttpServletResponse response, HttpServletRequest request, @RequestParam String username,
			@RequestParam String password, String flag) {
		// shiro 权限验证
		ShiroToken token = new ShiroToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		subject.login(token);
		Session session = subject.getSession();
		TpUser user = (TpUser) subject.getPrincipal();
		session.setAttribute("user", user);
		if ("1".equals(flag)) {
			setCookie(user, response, request);
		}
		return "1";
	}

	void setCookie(TpUser user, HttpServletResponse response, HttpServletRequest request) {
		// 创建Cookie
		Cookie nameCookie = new Cookie("shangname", user.getUsername());
		Cookie pswCookie = new Cookie("shangpsss", user.getPassword());
		// 设置Cookie的父路径
		nameCookie.setPath(request.getContextPath() + "/");
		pswCookie.setPath(request.getContextPath() + "/");
		//设置缓存日期
		nameCookie.setMaxAge(7 * 24 * 60 * 60);
		pswCookie.setMaxAge(7 * 24 * 60 * 60);
		// 加入Cookie到响应头
		response.addCookie(nameCookie);
		response.addCookie(pswCookie);
	}

	@RequestMapping("/logout")
	public String logout() {
		org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
		// subject.getSession().stop();
		subject.logout();
		return "common/login";
	}
}
